﻿using Dapper;
using System;
using BCEntity.Common.Service.WebsiteServiceItem;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Common.Service.WebsiteServiceItem
{
    /// <summary>
    /// 官网服务项目
    /// </summary>
    public class WebsiteServiceItemData : IWebsiteServiceItemData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM websiteserviceitem";
        private const string QUERY = @"SELECT WebsiteServiceItemId,LinkUrl,Enabled,CreateAdminId,CreateAdminName,CreateTime,UpdateTime,EditAdminId,EditAdminName,ServiceItemName,WebsiteServiceTypeId,ServiceTypeName,WebsiteBusinessCategoryId,Title,Description,Icon,Background FROM websiteserviceitem";
        public WebsiteServiceItemData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查官网服务项目是否存在
        public async Task<bool> Exists(int websiteServiceItemId)
        {
            string sql = string.Format(@"{0} WHERE WebsiteServiceItemId=?WebsiteServiceItemId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WebsiteServiceItemId", websiteServiceItemId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加官网服务项目
        public async Task<WebsiteServiceItemEntity> Add(WebsiteServiceItemEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("websiteserviceitem", new string[] { "CreateAdminId", "CreateAdminName","ServiceItemName", "WebsiteServiceTypeId", "ServiceTypeName", "WebsiteBusinessCategoryId", "Title" , "LinkUrl", "Description", "Icon", "Background" });
            sql = string.Format("{0} {1} WHERE WebsiteServiceItemId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?ServiceItemName", entity.ServiceItemName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WebsiteServiceTypeId", entity.WebsiteServiceTypeId, DbType.Int32, size: 11);
            parameters.Add("?ServiceTypeName", entity.ServiceTypeName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WebsiteBusinessCategoryId", entity.WebsiteBusinessCategoryId, DbType.Int32, size: 11);
            parameters.Add("?Title", entity.Title?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?LinkUrl", entity.LinkUrl?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?Description", entity.Description?.Trim(), DbType.String);
            parameters.Add("?Icon", entity.Icon?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?Background", entity.Background?.Trim(), DbType.AnsiString, size: 1000);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WebsiteServiceItemEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改官网服务项目
        public async Task<WebsiteServiceItemEntity> Update(WebsiteServiceItemEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("websiteserviceitem", new string[] { "LinkUrl", "EditAdminId", "EditAdminName", "ServiceItemName", "WebsiteServiceTypeId",
                "ServiceTypeName", "WebsiteBusinessCategoryId", "Title", "Description", "Icon", "Background" }, new string[] { "WebsiteServiceItemId" });
            sql = string.Format("{0} {1} WHERE WebsiteServiceItemId=?WebsiteServiceItemId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WebsiteServiceItemId", entity.WebsiteServiceItemId, DbType.Int32, size: 11);
            parameters.Add("?LinkUrl", entity.LinkUrl?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?ServiceItemName", entity.ServiceItemName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WebsiteServiceTypeId", entity.WebsiteServiceTypeId, DbType.Int32, size: 11);
            parameters.Add("?ServiceTypeName", entity.ServiceTypeName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WebsiteBusinessCategoryId", entity.WebsiteBusinessCategoryId, DbType.Int32, size: 11);
            parameters.Add("?Title", entity.Title?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?Description", entity.Description?.Trim(), DbType.String);
            parameters.Add("?Icon", entity.Icon?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?Background", entity.Background?.Trim(), DbType.AnsiString, size: 1000);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WebsiteServiceItemEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除官网服务项目
        public async Task<bool> Delete(int websiteServiceItemId)
        {
            string sql = @"DELETE FROM websiteserviceitem WHERE WebsiteServiceItemId=?WebsiteServiceItemId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WebsiteServiceItemId", websiteServiceItemId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取官网服务项目
        public async Task<WebsiteServiceItemEntity> GetEntity(int websiteServiceItemId)
        {
            string sql = string.Format(@"{0} WHERE WebsiteServiceItemId=?WebsiteServiceItemId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WebsiteServiceItemId", websiteServiceItemId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WebsiteServiceItemEntity>(sql, parameters);
        }
        #endregion

        #region 获取官网服务项目列表
        public async Task<IEnumerable<WebsiteServiceItemEntity>> GetList(int? websiteServiceTypeId)
        {
            if (websiteServiceTypeId.HasValue)
            {
                string sql = string.Format(@"{0} WHERE WebsiteServiceTypeId=?WebsiteServiceTypeId AND Enabled=1", QUERY);
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("?WebsiteServiceTypeId", websiteServiceTypeId, DbType.Int32);
                return await this.databaseContext.Slave.QueryAsync<WebsiteServiceItemEntity>(sql, parameters);
            }
            else
            {
                string sql = string.Format(@"{0} WHERE Enabled=1", QUERY);
                return await this.databaseContext.Slave.QueryAsync<WebsiteServiceItemEntity>(sql);
            }
        }
        #endregion

        #region 获取官网服务项目分页
        public async Task<(IEnumerable<WebsiteServiceItemEntity>, int)> Query(string businessCategoryTitle, string serviceTypeName, string serviceItemName, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(serviceTypeName))
            {
                wheres.Add("Title LIKE CONCAT('%',CONCAT(?Title,'%'))");
                parameters.Add("?Title", businessCategoryTitle?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(serviceTypeName))
            {
                wheres.Add("ServiceTypeName LIKE CONCAT('%',CONCAT(?ServiceTypeName,'%'))");
                parameters.Add("?ServiceTypeName", serviceTypeName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(serviceItemName))
            {
                wheres.Add("ServiceItemName LIKE CONCAT('%',CONCAT(?ServiceItemName,'%'))");
                parameters.Add("?ServiceItemName", serviceItemName?.Trim(), DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM websiteserviceitem {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<WebsiteServiceItemEntity, int>(sql, parameters);
        }
        #endregion

        #region 启用官网服务项目
        public async Task<bool> Enabled(int websiteServiceItemId)
        {
            string sql = @"UPDATE websiteserviceitem SET Enabled=1 WHERE WebsiteServiceItemId=?WebsiteServiceItemId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WebsiteServiceItemId", websiteServiceItemId, DbType.Int32);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 禁用官网服务项目
        public async Task<bool> Disabled(int websiteServiceItemId)
        {
            string sql = @"UPDATE websiteserviceitem SET Enabled=0 WHERE WebsiteServiceItemId=?WebsiteServiceItemId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WebsiteServiceItemId", websiteServiceItemId, DbType.Int32);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion
    }
}



